<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style>
    * {
      margin: 0;
      padding: 0;
    }
  </style>
</head>

<body>
  <canvas id="myCanvas" width="400" height="400"></canvas>

  <script>
    const myCanvas = document.getElementById('myCanvas');
    const ctx = myCanvas.getContext('2d');

    // 动态创建一个 img 节点
    let img = new Image();
    img.src = 'demo.png';

    // 必须保证图片资源已经加载完毕
    img.onload = function () {
      ctx.drawImage(img, 0, 0);
      // ctx.drawImage(img, 0, 0, 400, 400); // 缩放
      // ctx.drawImage(img, 0, 0, 100, 100, 0, 0, 200, 200);

      let imgData = ctx.getImageData(0, 0, 195, 200);
      let imgDataArr = imgData.data;
      console.log('获取像素数据：', imgData);

      for (var i = 0; i < imgDataArr.length; i += 8) {
        imgDataArr[i] = 255; // r
        imgDataArr[i + 1] = 255; // g
        imgDataArr[i + 2] = 255; // b
      }

      ctx.putImageData(imgData, 200, 0);
    }

  </script>
</body>

</html>